import React, { PureComponent } from 'react';
import Enumerable from 'linq';
import { connect } from 'dva';
import AccountJS from '@/utils/account';
import * as Utils from '@/utils/utils';
import Link from 'umi/link';
import moment from 'moment';

import { Drawer, Card, Form, Radio, Table, Alert, Button } from 'antd';

import styles from './styles.less';

const { Button: RadioButton, Group: RadioGroup } = Radio;

const ModelName = "receiveGroup";
@connect(({ loading, currency, user }) => ({
  loading: loading.models[ModelName],
  curs: currency.list,
  cUser: user.currentUser,
}))
@Form.create()
class Comp extends PureComponent {
  state = {
    data: [],
    clearType: 2,
    currencyId: 1,
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.currentItem !== this.props.currentItem) {
      if (nextProps.currentItem != null) {
        this.loadData(nextProps.currentItem);
      }
    }
  }

  loadData(currentItem) {
    const { dispatch } = this.props;
    const { qc, cUser } = this.props;

    this.setState({
      clearType: 0, // 未结清
      currencyId: 0, // 所有币种
    })

    const drawerQc = {
      userId: cUser.id,
      relationerId: currentItem.relationerId,
      currencyId: currentItem.currencyId,
      dateStart: qc.dateStart,
      dateEnd: qc.dateEnd
    }

    dispatch({
      type: `${ModelName}/relationerDetails`,
      payload: drawerQc,
      callback: (resp) => {
        this.setState({ data: resp });
      }
    })
  }

  genCSV(jsonData) {
    let str = ``;

    if (!jsonData || jsonData.length <= 0) {
      return;
    }

    const relationerName = jsonData[0]['relationerName'];

    str += relationerName;
    str += '\n';

    // 行数据
    let lineData = `单号, SO号, 年月, 金额, 结清, 欠结, 币种\n`;
    for (let i = 0; i < jsonData.length; i++) {

      let record = jsonData[i];

      let leftValue = record.receive - record.amount;

      var item = `${
        record.billNumber + ',\t' +
        record.so + ',\t' +
        record.year + '-' + record.month + ',\t' +
        record.amount + ',\t' +
        record.receive + ',\t' +
        leftValue + ',\t' +
        record.currencyName
        }`;
      lineData += item + ',\n'
    }
    str += lineData;

    //encodeURIComponent解决中文乱码
    let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
    //通过创建a标签实现
    let link = document.createElement("a");
    link.href = uri;
    //对下载的文件命名
    link.download = relationerName + ' ' + moment().format('YYYY-MM-DD') + ".csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  render() {
    const { loading, onClose, visible, relationer, curs, currentItem } = this.props;
    const { data, clearType } = this.state;

    const filterData = (data) => {
      var fData = data;
      // 结清未结清
      if (clearType == 1) {
        fData = data.filter(r => r.receive >= r.amount);
      } else if (clearType == 2) {
        fData = data.filter(r => r.receive < r.amount);
      }

      return fData;
    }

    const listTable = () => {

      const recLeftColumn = (record) => {
        let leftValue = record.receive - record.amount;

        if (leftValue >= 0) {
          return (<span>{AccountJS.formatMoney(leftValue, '')}</span>);
        }
        else {
          return (<span style={{ color: 'red' }}>{AccountJS.formatMoney(Math.abs(leftValue), '')}</span>);
        }
      }

      const columns = [
        {
          title: '#',
          dataIndex: 'ReNo',
          render: (text, record, index) => (
            <span> {index + 1} </span>
          ),
        },
        {
          title: '单号',
          dataIndex: 'billNumber',
          render: text => <Link to={`/Bill/${text}/INV`}>{text}</Link>,
        },
        {
          title: 'SO号',
          dataIndex: 'so',
        },
        {
          title: '年月',
          dataIndex: 'year-month',
          align: 'right',
          render: (text, record) => <span>{record.year + '-' + record.month}</span>,
        },
        {
          title: '金额',
          dataIndex: 'amount',
          align: 'right',
          render: (text, record) => <span>{AccountJS.format(record.amount, 2)}</span>,
        },

        {
          title: '结清',
          dataIndex: 'receive',
          align: 'right',
          render: (text, record) => <span>{AccountJS.format(record.receive, 2)}</span>,
        },
        {
          title: '欠结',
          dataIndex: 'receiveLeft',
          align: 'right',
          render: (text, record) => recLeftColumn(record),
        },
        {
          title: '币种',
          dataIndex: 'currencyName',
        },
        {
          title: '类型',
          dataIndex: 'invoiceType',
          render: (text, record) => ['', '应收', '应收', '应付'][record.invoiceType],
        },
        {
          title: '核销',
          dataIndex: 'isRecLock',
          render: (text, record) => (
            <span>
              {record.isRecLock === 1 ? Utils.getChineseDate(record.recLockDate, '已核销') : '未核销'}{' '}
            </span>
          ),
        },
      ];

      const alertHeader = (filteredData) => {
        if (filteredData.length <= 0) return null;

        var groupSum = Enumerable.from(filteredData).groupBy("$.currencyName", null,
          function (key, g) {
            var result = {
              currencyName: key,
              totalReceive: g.sum("$.receive"),
              totalAmount: g.sum("$.amount")
            }
            return result;
          }).toArray();

        var groupStr = groupSum.map(item => {
          var recLeft = AccountJS.format(item.totalReceive - item.totalAmount);
          return (
            <div key={item.currencyName}>
              <span style={{ width: '5em' }}><span className={styles.currencyName}>{item.currencyName}:</span>{AccountJS.format(item.totalAmount, 2)}</span>
              <span style={{ marginLeft: '1em', width: '10em' }}><span className={styles.currencyName}>CLEARED:</span>{AccountJS.format(item.totalReceive, 2)}</span>
              <span style={{ marginLeft: '1em', width: '10em' }}><span className={styles.currencyName}>LEFT:</span>{AccountJS.format(recLeft, 2)}</span>
            </div>);
        })

        return (<Alert
          style={{ marginTop: '12px', fontSize: '20' }}
          // showIcon type="info"
          message={groupStr}
        />);
      }

      return (
        <div>
          {alertHeader(filterData(data))}
          <Table
            rowKey={record => `${record.invoiceId + '-' + record.currencyId}`}
            size="small"
            style={{ marginTop: 12 }}
            loading={loading}
            dataSource={filterData(data)}
            rowClassName={record => record.currencyName === 'USD' ? styles.USD : ''}
            columns={columns}
            pagination={{
              showSizeChanger: true,
              pageSize: 200,
              showTotal: (total, range) => `共${total}项，当前显示 ${range[0]}-${range[1]}`,
            }}
          />
        </div>
      )
    }

    const extraContent = (
      <div className={styles.extraContent}>
        <RadioGroup
          defaultValue={clearType}
          onChange={e => {
            e.preventDefault();
            this.setState({ clearType: e.target.value });
          }}
        >
          <RadioButton value={0}>全部</RadioButton>
          <RadioButton value={1}>已结清</RadioButton>
          <RadioButton value={2}>未结清</RadioButton>
        </RadioGroup>
        <Button type="primary" style={{ marginLeft: '32px' }} onClick={() => this.genCSV(filterData(data))} >下载</Button>

      </div>
    );

    return (<div className={styles.container}>
      <Drawer
        width={1080}
        closable={false}
        onClose={onClose}
        visible={visible}
        style={{
          overflow: 'auto',
          height: 'calc(100% - 108px)',
          paddingBottom: '108px',
        }} >
        <Card title={currentItem && currentItem.relationerName} extra={extraContent}>
          {listTable()}
        </Card>
      </Drawer>
    </div>);

  }
}

export default Comp;

